﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace Tum.CollabXT.Wizard
{
    /// <summary>
    /// Interaction logic for InitializingProcessProvider.xaml
    /// </summary>
    public partial class InitializingProcessProvider : Window
    {
        /// <summary>
        /// Conversion workflow.
        /// </summary>
        internal ConversionWorkflow Workflow
        {
            get { return _Workflow; }
            set { _Workflow = value; }
        }
        private ConversionWorkflow _Workflow;

        /// <summary>
        /// Instance of the processing thread.
        /// </summary>
        Thread ProcessingThreadInstance = null;


        /// <summary>
        /// Constructor.
        /// </summary>
        public InitializingProcessProvider()
        {
            InitializeComponent();

            progressBar.Value = 50;
        }

        /// <summary>
        /// Thread that handles the process provider initialization.
        /// </summary>
        private void ProcessingThread()
        {
            if (Workflow != null && Workflow.Project.ProcessProvider != null)
            {
                try
                {
                    Workflow.Project.ProcessProvider.Instance.Initialize(Workflow.Log);
                    this.Dispatcher.Invoke(new SetDialogResultDelegate(SetDialogResult), true);
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("An error occured while initializing process provider.\n\n{0}\n\n@{1}", e.Message, e.StackTrace));
                    this.Dispatcher.Invoke(new SetDialogResultDelegate(SetDialogResult), false);
                }
            }
            this.Dispatcher.Invoke(new ThreadStart(Close), null);
        }

        /// <summary>
        /// Delegate type for SetDialogResult.
        /// </summary>
        /// <param name="result">Dialog result.</param>
        private delegate void SetDialogResultDelegate(bool result);

        /// <summary>
        /// Sets the dialog result.
        /// </summary>
        /// <param name="result">Dialog result.</param>
        private void SetDialogResult(bool result)
        {
            DialogResult = result;
        }


        /// <summary>
        /// Event handler for visibility changes.
        /// </summary>
        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (IsVisible && ProcessingThreadInstance == null)
            {
                //Start processing
                ProcessingThreadInstance = new Thread(ProcessingThread);
                ProcessingThreadInstance.Start();
            }
        }
    }
}
